
package com.yimixian.app.common;

import com.umeng.analytics.MobclickAgent;
import com.yimixian.app.BuildConfig;
import com.yimixian.app.R;
import com.yimixian.app.activity.YMXMainActivity;
import com.yimixian.app.address.ChooseAddressOrStoreActivity;
import com.yimixian.app.address.ShowAddressesActivity;
import com.yimixian.app.cart.CartDetailActivity;
import com.yimixian.app.cart.CartManager;
import com.yimixian.app.data.DataManager;
import com.yimixian.app.goods.GoodDetailActivity;
import com.yimixian.app.goods.GoodDetailTopFragment;
import com.yimixian.app.model.Address;
import com.yimixian.app.model.AppConfig;
import com.yimixian.app.model.Coordinate;
import com.yimixian.app.model.GoodsItem;
import com.yimixian.app.model.Store;
import com.yimixian.app.order.ConfirmOrderActivity;
import com.yimixian.app.order.OrderDetailActivity;
import com.yimixian.app.store.StoreDetailActivity;
import com.yimixian.app.ui.ProgressDialogFragment;
import com.yimixian.app.ui.ShareBoardView;
import com.yimixian.app.ui.pull.PullRefreshLayout;
import com.yimixian.app.user.UserRegistrationActivity;
import com.yimixian.app.util.DateUtil;
import com.yimixian.app.util.PayUtils;
import com.yimixian.app.util.SharedPreferencesHelper;
import com.yimixian.app.util.StringUtils;
import com.yimixian.app.util.Strings;
import com.yimixian.app.util.UiUtils;
import com.yimixian.app.util.WeChatUtils;

import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import butterknife.ButterKnife;
import butterknife.InjectView;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

public class WebViewActivity extends WebViewHttpActivity {

    public static final String EXTRA_TITLE = "extra_title";
    public static final String EXTRA_URL = "extra_url";
    public static final String EXTRA_SHARE_RESULT = "extra_share_result";

    public static final String WX_SHARE = "wx_share";
    public static final String FRIEND_CIRCLE_SHARE = "friend_circle_share";
    public static final String STORE_ID = "store_id";

    private ValueCallback<Uri> mUploadMessage;
    private final static int FILECHOOSER_RESULTCODE = 1;
    @InjectView(R.id.webview)
    WebView mWebView;
    @InjectView(R.id.hide_webview)
    WebView mHideWebView;
    @InjectView(R.id.main_frame)
    FrameLayout mMainFrame;
    @InjectView(R.id.progress_bar)
    ProgressBar mProgressBar;

    private DataManager mDataManager;
    private ShareBoardView mShareBoardView;
    private String mTitle;
    private String mUrl;
    private String mCallBack;
    private boolean mHasShareStarted = false;
    private boolean mIsShareBoardViewShowed = false;
    Uri photoUri = null;
    private Bitmap mSharePic = null;
    private boolean mIsLoadPicSuccess = true;
    private String mShareClickedState = "";
    private int mRetryShareCount = 0;
    private ProgressDialogFragment mProgressDialogFragment;
    private PullRefreshLayout refresh_layout;
    private Handler mHandler = new Handler();
    private String storeId = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getIntent().hasExtra(EXTRA_URL)) {
            mUrl = getIntent().getStringExtra(EXTRA_URL);
            mTitle = getIntent().getStringExtra(EXTRA_TITLE);
        } else if (savedInstanceState.containsKey(EXTRA_URL)) {
            mUrl = savedInstanceState.getString(EXTRA_URL);
            mTitle = savedInstanceState.getString(EXTRA_TITLE);
        } else {
            finish();
        }
        if (TextUtils.isEmpty(mUrl)) {
            finish();
            return;
        }
        Uri uri = Uri.parse(mUrl);
        if (uri.getScheme() != null && uri.getScheme().equals("ymxian")) {
            dealCustomProtocol(uri);
            finish();
            return;
        }
        if (Build.VERSION.SDK_INT >= 21) {
            WebView.enableSlowWholeDocumentDraw();
        }
        setContentView(R.layout.webview_activity);
        ButterKnife.inject(this);
        if (mUrl.contains("addSuccess") || mUrl.contains("addFail")) {
            backButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(YMXMainActivity.buildIntentHomeTabSection(WebViewActivity.this,
                            ""));
                }
            });
        }
        mDataManager = DataManager.getInstance();
//        setAddressIdCookie();

        Store store = SharedPreferencesHelper.getStore(SharePreferenceKeys.CURRENT_STORE);
        if(store != null){
            storeId = store.id + "";
        }else{
            storeId = getIntent().getIntExtra(STORE_ID, -1) + "";
        }
        setStoreIdCookie();
        setAddressIdCookie();


        WebSettings settings = mWebView.getSettings();
        settings.setSupportZoom(false);
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setBlockNetworkImage(false);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setUserAgentString(settings.getUserAgentString() + " YMXian/"
                + mDataManager.get(CacheKeys.VERSION_NAME));
        setWebViewDebugEnable(mWebView);
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse(url);
                if (uri.getScheme() != null && uri.getScheme().equals("ymxian")) {
                    dealCustomProtocol(uri);
                } else {
                    if (url.endsWith(".apk")) {
                        Intent viewIntent = new Intent(Intent.ACTION_VIEW, uri);
                        startActivity(viewIntent);
                        return true;
                    }
                    view.loadUrl(appendTokenIfNecessary(url));
                }
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (refresh_layout != null) {
                    refresh_layout.setRefreshing(false);
                }
            }

        });
        mWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int progress) {
                if (progress < 100 && mProgressBar.getVisibility() == ProgressBar.INVISIBLE) {
                    mProgressBar.setVisibility(View.VISIBLE);
                }
                mProgressBar.setProgress(progress);
                if (progress == 100) {
                    mProgressBar.setVisibility(View.INVISIBLE);
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (TextUtils.isEmpty(mTitle)) {
                    mTitle = title;
                    refreshTitleText();
                }
                super.onReceivedTitle(view, title);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                showSelectDialog(uploadMsg, "", "");
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback uploadMsg, String acceptType) {
                showSelectDialog(uploadMsg, acceptType, "");
            }

            // For Android 4.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType,
                                        String capture) {
                showSelectDialog(uploadMsg, acceptType, capture);
            }

            // For Android 5.0.1
            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {

                String acceptTypes[] = fileChooserParams.getAcceptTypes();

                String acceptType = "";
                for (int i = 0; i < acceptTypes.length; ++i) {
                    if (acceptTypes[i] != null && acceptTypes[i].length() != 0)
                        acceptType += acceptTypes[i] + ";";
                }
                if (acceptType.length() == 0)
                    acceptType = "*/*";

                final ValueCallback<Uri[]> finalFilePathCallback = filePathCallback;

                ValueCallback<Uri> vc = new ValueCallback<Uri>() {

                    @Override
                    public void onReceiveValue(Uri value) {

                        Uri[] result;
                        if (value != null)
                            result = new Uri[]{
                                    value
                            };
                        else
                            result = null;

                        finalFilePathCallback.onReceiveValue(result);
                    }

                };
                showSelectDialog(vc, acceptType, "filesystem");
                // openFileChooser(vc, acceptType, "filesystem");
                return true;
            }
        });

        mUrl = appendTokenIfNecessary(mUrl);
        mWebView.loadUrl(mUrl);
        refreshTitleText();
        showCloseButton();
        backButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mWebView.canGoBack()) {
                    mWebView.goBack();
                } else {
                    finish();
                }
            }
        });

        refresh_layout = (PullRefreshLayout) findViewById(R.id.refresh_layout);
        refresh_layout.setRefreshStyle(PullRefreshLayout.YMX_PULL_DRAWABLE);
        refresh_layout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (mWebView != null) {
                            mWebView.reload();
                        }
                    }
                }, 800);
            }
        });

        mWebView.setOnTouchListener(new View.OnTouchListener() {

            private float mTouchSlop = ViewConfiguration.get(WebViewActivity.this).getScaledTouchSlop();
            private float downY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if(mWebView != null && mWebView.getScrollY() > 0){
                    refresh_layout.setEnabled(false);
                }else{
                    refresh_layout.setEnabled(true);
                }

//                switch (event.getAction()){
//                    case MotionEvent.ACTION_DOWN:
//                        downY = event.getRawY();
//                        break;
//                    case MotionEvent.ACTION_MOVE:
//                    case MotionEvent.ACTION_UP:
//                        if(downY - event.getRawY() < 0 && Math.abs(downY - event.getRawY()) > mTouchSlop){
//                            if(mWebView != null && mWebView.getScrollY() == 0){
//                                refresh_layout.dispatchTouchEvent(event);
//                                return true;
//                            }
//                        }
//                        break;
//                }

                return false;
            }
        });
    }

    private String appendTokenIfNecessary(String url) {
        String token = mDataManager.get(CacheKeys.TOKEN);
        Uri uri = Uri.parse(url);
        if (TextUtils.isEmpty(uri.getHost())) {
            return url;
        }
        if (Strings.isNullOrEmpty(token) || !uri.getHost().endsWith(".1mxian.com")) {
            return url;
        }
        return url + (url.contains("?") ? "&token=" : "?token=") + token;
    }


    private void setStoreIdCookie(){
        if(storeId != null && !"".equals(storeId.trim()) && !"-1".equals(storeId.trim())){
            CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
            cookieSyncManager.startSync();
            AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
            if (appConfig == null) {
                return;
            }
            if (appConfig.cookieDomains == null) {
                return;
            }
            for (int i = 0; i < appConfig.cookieDomains.size(); i++) {
                String Domain = appConfig.cookieDomains.get(i);
                CookieManager cookieManager = CookieManager.getInstance();
                cookieManager.setAcceptCookie(true);
                cookieManager.setCookie("http://"+Domain+"/", "store_id=" + storeId +  ";Path=/");
                CookieSyncManager.getInstance().sync();
            }
        }
    }

    private void setAddressIdCookie() {
        CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(this);
        cookieSyncManager.startSync();
        Address mAddress = SharedPreferencesHelper.getAddress(SharePreferenceKeys.CURRENT_ADDRESS);
        if (mAddress == null || mAddress.id == 0)
            return;
        AppConfig appConfig = mDataManager.get(CacheKeys.APP_CONFIG);
        if (appConfig == null) {
            return;
        }
        if (appConfig.cookieDomains == null) {
            return;
        }
        for (int i = 0; i < appConfig.cookieDomains.size(); i++) {
            String Domain = appConfig.cookieDomains.get(i);
            int addressId = mAddress.id;
            CookieManager cookieManager = CookieManager.getInstance();
            cookieManager.setCookie("http://"+Domain+"/", "address_id=" + addressId + ";Path=/");
            CookieSyncManager.getInstance().sync();
        }

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mIsShareBoardViewShowed) {
            mIsShareBoardViewShowed = false;
            mShareBoardView.close();
            return true;
        }
        if (keyCode == KeyEvent.KEYCODE_BACK && mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected String getTitleBarText() {
        return mTitle;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mHasShareStarted) {
            mHasShareStarted = false;
            onShareFinished();
        }
        if (PayUtils.getInstance().mStartedWechatPay) {
            PayUtils.getInstance().onWechatPayFinished();
        }

        //当用户把当前应用切换到前台展示时触发改时间
        if(mWebView != null){
            mWebView.loadUrl("javascript:window.dispatchEvent(new Event('ym.app_active'));");
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        removeCookie(this);
        if (mSharePic != null) {
            mSharePic.recycle();
            mSharePic = null;
        }
    }

    private void removeCookie(Context context) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        CookieSyncManager.getInstance().sync();
    }

    private void onShareFinished() {
        Object result = mDataManager.get(WebViewActivity.EXTRA_SHARE_RESULT);
        if (result != null && !TextUtils.isEmpty(mCallBack)) {
            if (((int) result) == WeChatUtils.WE_CHAT_SHARE_SUCCESS) {
                mWebView.loadUrl("javascript:" + mCallBack + "(1)");
                mDataManager
                        .put(WebViewActivity.EXTRA_SHARE_RESULT, WeChatUtils.WE_CHAT_SHARE_REST);
            } else if ((int) result == WeChatUtils.WE_CHAT_SHARE_FAIL) {
                mWebView.loadUrl("javascript:" + mCallBack + "(0)");
                mDataManager
                        .put(WebViewActivity.EXTRA_SHARE_RESULT, WeChatUtils.WE_CHAT_SHARE_REST);
            }
            mCallBack = "";
        }
    }

    private void dealCustomProtocol(final Uri uri) {
        Intent intent;
        if (uri.getHost() == null) {
            finish();
            return;
        }
        switch (uri.getHost()) {
            case ("login"):
                mCallBack = uri.getQueryParameter("callback");
                intent = new Intent(WebViewActivity.this, UserRegistrationActivity.class);
                startActivityForResult(intent, Constants.USER_REGISTRATION_REQUEST_CODE);
                break;
            case ("push_webview"):
                String weburl = "";
                weburl = uri.getQueryParameter("url");
                try {
                    if (!TextUtils.isEmpty(weburl)) {
                        weburl = URLDecoder.decode(weburl, "utf-8");
                        Intent intentAccount = new Intent(this, WebViewActivity.class);
                        intentAccount.putExtra(WebViewActivity.EXTRA_TITLE, "");
                        intentAccount.putExtra(WebViewActivity.EXTRA_URL, weburl);
                        startActivity(intentAccount);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                break;
            case ("close"):
                finish();
                break;
            case ("share"):
                // 生成bitmap
                String url = "";
                url = uri.getQueryParameter("snapshot_link");
                String url1 = "";
                try {
                    if (url != null) {
                        url1 = URLDecoder.decode(url, "utf-8");
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                final String snapshotLink = url1;
                // final String snapshotLink =
                // "http://x.1mxian.com/sharePage/test";
                mRetryShareCount = 0;
                mIsLoadPicSuccess = true;
                mSharePic = null;

                if (!TextUtils.isEmpty(snapshotLink) && mHideWebView != null) {
                    mHideWebView.setVerticalScrollBarEnabled(false); // 垂直不显示
                    mHideWebView.getSettings().setJavaScriptEnabled(true);
                    mHideWebView.loadUrl(snapshotLink);
                    mHideWebView.setDrawingCacheEnabled(true);
                    mHideWebView.setWebViewClient(new WebViewClient() {
                        public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
                            view.loadUrl(url);
                            return true;
                        }

                        @Override
                        public void onPageFinished(WebView view, String url) {
                            super.onPageFinished(view, url);
                            new Background().execute();
                        }

                        @Override
                        public void onPageStarted(WebView view, String url, Bitmap favicon) {
                            super.onPageStarted(view, url, favicon);
                        }

                        @Override
                        public void onReceivedError(WebView view, int errorCode,
                                String description,
                                String failingUrl) {
                            super.onReceivedError(view, errorCode, description, failingUrl);
                            mIsLoadPicSuccess = false;
                            if (mProgressDialogFragment != null) {
                                mProgressDialogFragment.dismiss();
                            }
                            if (mRetryShareCount > 0) {
                                shareFailed();
                            }
                        }
                    });
                }
                MobclickAgent.onEvent(this, StatConstants.MY_INVITE_FRIENDS_SHARE_CLICK);
                String rangeStr = uri.getQueryParameter("range");
                int range = 0;
                if (!TextUtils.isEmpty(rangeStr)) {
                    range = Integer.parseInt(rangeStr.trim());
                }
                String directStr = uri.getQueryParameter("direct");
                int direct = 0;
                if (!TextUtils.isEmpty(directStr)) {
                    direct = Integer.parseInt(directStr.trim());
                }
                mShareBoardView = new ShareBoardView(WebViewActivity.this);
                if (0 == range || 0 == direct) {
                    mMainFrame.addView(mShareBoardView);
                }
                mCallBack = uri.getQueryParameter("callback");
                mIsShareBoardViewShowed = true;
                mShareBoardView.setWeChatFriendAndCircleViewClickListener(
                        new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // mShareClickedState = WX_SHARE;
                                shareWechatFirend(uri);
                                mShareBoardView.close();
                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mProgressDialogFragment = UiUtils
                                        .showProgressDialog(WebViewActivity.this, "分享中");
                                mShareClickedState = FRIEND_CIRCLE_SHARE;
                                mHasShareStarted = true;
                                mIsShareBoardViewShowed = false;
                                if (TextUtils.isEmpty(snapshotLink)) {
                                    if (mProgressDialogFragment != null) {
                                        mProgressDialogFragment.dismiss();
                                    }
                                    WeChatUtils.getInstance().sendWeChatMessage(
                                            WebViewActivity.this,
                                            uri, WeChatUtils.ShareType.WECHAT_CIRCLE);
                                } else {
                                    if (mSharePic != null) {
                                        if (mIsLoadPicSuccess) {
                                            if (mProgressDialogFragment != null) {
                                                mProgressDialogFragment.dismiss();
                                            }
                                            WeChatUtils.getInstance().shareImage(
                                                    WebViewActivity.this,
                                                    mSharePic, WeChatUtils.ShareType.WECHAT_CIRCLE);
                                        } else {
                                            shareFailed();
                                        }
                                    } else {
                                        reLoadSharePic(snapshotLink);
                                    }
                                }
                                mShareBoardView.close();
                            }
                        });
                if (range == 0) {
                    mShareBoardView.showAll();
                } else if (range == 1) {
                    if (1 == direct) {
                        shareWechatFirend(uri);
                    } else {
                        mShareBoardView.hideWeChatCircleShareView();
                    }
                } else if (range == 2) {
                    if (1 == direct) {
                        mProgressDialogFragment = UiUtils
                                .showProgressDialog(WebViewActivity.this, "分享中");
                        mHasShareStarted = true;
                        mIsShareBoardViewShowed = false;
                        if (mProgressDialogFragment != null) {
                            mProgressDialogFragment.dismiss();
                        }
                        WeChatUtils.getInstance().sendWeChatMessage(
                                WebViewActivity.this,
                                uri, WeChatUtils.ShareType.WECHAT_CIRCLE);
                    } else {
                        mShareBoardView.hideWeChatFriendShareView();
                    }
                }
                break;
            case ("show_store"):
                intent = new Intent(WebViewActivity.this, StoreDetailActivity.class);
                intent.putExtra(StoreDetailActivity.EXTRA_STORE_ID,
                        uri.getQueryParameter("store_id"));
                startActivity(intent);
                break;
            case ("tel"):
                String phone_number = uri.getQueryParameter("phone_number");
                Intent intentContact = new Intent(Intent.ACTION_CALL);
                intentContact.setAction(Intent.ACTION_DIAL);
                intentContact.setData(Uri.parse("tel:" + phone_number));
                startActivity(intentContact);
                break;
            case ("gohome"):
                startActivity(YMXMainActivity.buildExitIntent(this, false));
                break;
            case ("showmap"):
                intent = new Intent(WebViewActivity.this, MarkLocationMapActivity.class);
                intent.putExtra(
                        MarkLocationMapActivity.EXTRA_COORDINATE,
                        new Coordinate(
                                Constants.BAIDU_COORD_SYSTEM, uri.getQueryParameter("long"), uri
                                        .getQueryParameter("lat")));
                String title = uri.getQueryParameter("title");
                if (!TextUtils.isEmpty(title)) {
                    intent.putExtra(MarkLocationMapActivity.EXTRA_TITLE, title);
                }
                String level = uri.getQueryParameter("level");
                if (!TextUtils.isEmpty(level)) {
                    intent.putExtra(MarkLocationMapActivity.EXTRA_LEVEL, level);
                }
                startActivity(intent);
                break;
            case ("pay"):
                String payId = uri.getQueryParameter("payment_id");
                String callBack = uri.getQueryParameter("callback");
                String payMethod = uri.getQueryParameter("payment_method");
                if (TextUtils.isEmpty(payMethod)) {
                    payMethod = ConfirmOrderActivity.PAYMENT_METHOD_WECHAT;
                }
                PayUtils.getInstance().setWebView(mWebView);
                PayUtils.getInstance().setActivity(this);
                PayUtils.getInstance().setCallBack(callBack);
                PayUtils.getInstance().startPay(payMethod, payId);
                break;
            case ("product"):
                String GoodId = uri.getQueryParameter("pid");
                startActivityForResult(GoodDetailActivity.buildIntent(this, GoodId), GoodDetailTopFragment.RETURN_TO_CATEGORY);
                break;
            case ("show_cart"):
                DateUtil.setCityUMeng(null, UMengConstants.NEW_BOTTOM_CARTBTN);
                startActivity(CartDetailActivity.buildIntent(this));
                break;
            case ("show_section"):
                String sectionId = uri.getQueryParameter("section_id");
                startActivity(YMXMainActivity.buildIntentSessionActivity(this, sectionId));
                break;
            case ("show_category"):
                startActivity(YMXMainActivity.buildIntentTab(this, YMXMainActivity.TAB_KIND));
                break;
            case ("address"):
                mCallBack = uri.getQueryParameter("callback");
                intent = new Intent(WebViewActivity.this, ChooseAddressOrStoreActivity.class);
                intent.putExtra(ShowAddressesActivity.EXTRA_MODE,
                        ShowAddressesActivity.PICK_ADDRESS_MODE);
                startActivityForResult(intent, Constants.WEBVIEW_CHOOSE_ADDRESS_REQUEST_CODE);
                break;
            case ("order_detail"):
                int orderId = Integer.parseInt(uri.getQueryParameter("order_id"));
                Intent orderIntent = new Intent(this, OrderDetailActivity.class);
                orderIntent.putExtra(OrderDetailActivity.EXTRA_ORDER_ID, orderId);
                startActivity(orderIntent);
                break;
            case ("cart_good_modify"):
                int goodId = Integer.parseInt(uri.getQueryParameter("good_id"));
                int change = Integer.parseInt(uri.getQueryParameter("change"));
                mCallBack = uri.getQueryParameter("callback");
                onPlusOrMinusHttp(change, goodId);
                break;
            case("get_clipboard"):
                ClipboardManager cmb = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
                mWebView.loadUrl("javascript:" + uri.getQueryParameter("callback") + "('" + cmb.getText() + "')");
                break;
            case("get_cartdata"):
                Map<Integer, GoodsItem> map = null;
                if(DataManager.getInstance().get(CacheKeys.TOKEN) != null){
                    map = CartManager.getInstance().mCartGoodsItems;
                }else{
                    map = CartManager.offLineCartMap;
                }
                String result = "";
                if(map != null && map.keySet().size() > 0){
                    String countStr = "";
                    float totalPrice = 0;
                    for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) {
                        Integer id = (Integer) iterator.next();
                        GoodsItem item = map.get(id);
                        int count = Integer.parseInt(item.count);
                        if(count > 0){
                            countStr += "\"" + id + "\":"+ count + ",";
                            totalPrice += Float.parseFloat(item.unitPrice) * count;
                        }
                    }
                    if(!Strings.isNullOrEmpty(countStr) && totalPrice != 0) {
                        countStr = countStr.substring(0, countStr.length() - 1);
                        result = "{\"count\":{" + countStr + "}, \"total_price\":\"总价￥" + totalPrice + "\"}";
                    }
                }
                mWebView.loadUrl("javascript:" + uri.getQueryParameter("callback") + "('" + result + "')");
                break;
            default:
                break;
        }

    }

    @Override
    public void cartChangeResult(int status) {
        if (mWebView != null) {
            mWebView.loadUrl("javascript:" + mCallBack + "(" + status + ")");
        }
    }

    /**
     * 分享微信好友
     * 
     * @param uri
     */
    private void shareWechatFirend(Uri uri) {
        mProgressDialogFragment = UiUtils
                .showProgressDialog(WebViewActivity.this, "分享中");
        mHasShareStarted = true;
        mIsShareBoardViewShowed = false;
        if (mProgressDialogFragment != null) {
            mProgressDialogFragment.dismiss();
        }
        WeChatUtils.getInstance().sendWeChatMessage(
                WebViewActivity.this,
                uri, WeChatUtils.ShareType.WECHAT_FRIEND);
    }

    private void shareFailed() {
        UiUtils.showToast("分享失败");
        if (mProgressDialogFragment != null) {
            mProgressDialogFragment.dismiss();
        }
    }

    /**
     * 重新加载要分享的图片
     */
    private void reLoadSharePic(String snapshotLink) {
        if (mRetryShareCount < 1 && mHideWebView != null) {
            mRetryShareCount++;
            mIsLoadPicSuccess = true;
            mHideWebView.loadUrl(snapshotLink);
        } else {
            shareFailed();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage)
                return;
            Uri result = data == null || resultCode != RESULT_OK ? null
                    : data.getData();
            if (result == null) {
                // 拍照成功
                if (resultCode == -1)
                    if (photoUri != null) {
                        result = photoUri;
                    }
            }
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
        if (requestCode == Constants.USER_REGISTRATION_REQUEST_CODE
                && !TextUtils.isEmpty(mCallBack)) {
            if (resultCode == RESULT_OK) {
                mWebView.loadUrl("javascript:" + mCallBack + "(1)");
            } else {
                mWebView.loadUrl("javascript:" + mCallBack + "(0)");
            }
            mCallBack = "";
        }
        if (requestCode == Constants.WEBVIEW_CHOOSE_ADDRESS_REQUEST_CODE
                && !TextUtils.isEmpty(mCallBack)) {
            if (resultCode == RESULT_OK) {
                setAddressIdCookie();
                mWebView.loadUrl("javascript:" + mCallBack + "()");
            }
            mCallBack = "";
        }
        //商品详情跳转分类
        if(requestCode == GoodDetailTopFragment.RETURN_TO_CATEGORY
                && resultCode == GoodDetailTopFragment.RETURN_TO_CATEGORY){
            finish();
        }
    }

    public void setWebViewDebugEnable(WebView webView) {
        if (BuildConfig.SERVER_ENVIRONMENT != Constants.ServerEnvironment.Release)
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webView.setWebContentsDebuggingEnabled(true);
            }
    }

    public void showSelectDialog(final ValueCallback<Uri> uploadMsg, final String acceptType,
            final String capture) {
        mUploadMessage = uploadMsg;
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setOnCancelListener(new ReOnCancelListener());
        alertDialog.setTitle("请选择");
        final CharSequence[] charSequences = {
                "拍照", "图库"
        };

        alertDialog.setItems(charSequences, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    TakePhoto(uploadMsg, acceptType,
                        capture);
                } else {
                    setImage(uploadMsg, acceptType,
                        capture);
                }
            }
        });
        AlertDialog dialog = alertDialog.create();
        dialog.getWindow().setWindowAnimations(R.style.popup_in_center);
        dialog.show();
    }

    public void TakePhoto(ValueCallback<Uri> uploadMsg, String acceptType,
            String capture) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        i.addCategory("android.intent.category.DEFAULT");
        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
                "yyyy_MM_dd_HH_mm_ss");
        String filename = timeStampFormat.format(new Date());
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, filename);
        photoUri = getContentResolver().insert(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
        i.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "拍照"),
                WebViewActivity.FILECHOOSER_RESULTCODE);

    }

    public void setImage(ValueCallback<Uri> uploadMsg, String acceptType,
            String capture) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        WebViewActivity.this.startActivityForResult(Intent.createChooser(i, "选择上传图片"),
                FILECHOOSER_RESULTCODE);
    }

    private class ReOnCancelListener implements DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMessage != null) {
                mUploadMessage.onReceiveValue(null);
                mUploadMessage = null;
            }
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    class Background extends AsyncTask<Void, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(Void... params) {
            try {
                Thread.sleep(2000);
                return getBitmap();
            } catch (InterruptedException e) {
            } catch (Exception e) {
            }
            return null;
        }

        @Override
        protected void onPostExecute(Bitmap result) {
            if (result != null) {
                // 分享图片
                mSharePic = result;
                if (mIsLoadPicSuccess && mRetryShareCount > 0) {
                    if (WX_SHARE.equals(mShareClickedState)) {
                        WeChatUtils.getInstance().shareImage(WebViewActivity.this, mSharePic,
                                WeChatUtils.ShareType.WECHAT_FRIEND);
                        if (mShareBoardView != null) {
                            mShareBoardView.close();
                        }
                    } else if (FRIEND_CIRCLE_SHARE.equals(mShareClickedState)) {
                        WeChatUtils.getInstance().shareImage(WebViewActivity.this, mSharePic,
                                WeChatUtils.ShareType.WECHAT_CIRCLE);
                        if (mShareBoardView != null) {
                            mShareBoardView.close();
                        }
                    }
                }
                if (mProgressDialogFragment != null) {
                    mProgressDialogFragment.dismiss();
                }
                mShareClickedState = "";
            } else {
                shareFailed();
            }
        }
    }

    @NonNull
    private Bitmap getBitmap() {
        if (mHideWebView == null) {
            return null;
        }
        mHideWebView.measure(0, 0);
        int screenWidth = mHideWebView.getMeasuredWidth();
        int screenHeight = mHideWebView.getMeasuredHeight();
        Bitmap bitmap = Bitmap.createBitmap(screenWidth, screenHeight, Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(bitmap);
        mHideWebView.draw(canvas);
        return bitmap;
    }
}
